<template>
  <PageWrapper>
    <a-card>
      <a-row>
        <a-space>
          <a-upload
            :before-upload="onPackageUploadSuccess"
            v-model:file-list="fileList"
            :auto-upload="false"
            :show-file-list="false"
            accept=".zip,.tar,.7z,.gz"
          >
            <a-button
              type="primary"
              :loading="uploadLoading"
              :disabled="uploadLoading"
            >{{ $t("common.upload") }}
            </a-button
            >
          </a-upload>
          <a-button type="primary" @click="fnBatchDelete">{{ $t("osManager.batchDelete") }}</a-button>

          <a-button type="primary" :icon="h(SyncOutlined)" @click="initPage"></a-button>
        </a-space>
      </a-row>
      <a-table
          row-key="asset_id"
          :data-source="packageList"
          :columns="packageColumns"
          :pagination="pagination"
          :loading="loading"
          :row-selection="{
            selectedRowKeys: selectedRowKeys,
            onChange: onSelectChange,
          }"
      >
        <template #bodyCell="{ record, column }">
          <template v-if="column.dataIndex === 'operation'">
            <a-tooltip :title="$t('common.delete')">
              <a-button  size="small" type="text" @click="fnDeletePackage(record)">
                <DeleteOutlined/>
              </a-button>
            </a-tooltip>
            <a-tooltip :title="$t('packageManage.download')">
              <a-button size="small" type="text" @click="fnDownloadReport(record)">
                <DownloadOutlined/>
              </a-button>
            </a-tooltip>
          </template>
          <span v-else>{{ record[column.dataIndex] ? record[column.dataIndex] : '--' }}</span>
        </template>
      </a-table>
    </a-card>
  </PageWrapper>
</template>

<script>
import { api } from '@/api'
import { message } from 'ant-design-vue';
import { Modal } from 'ant-design-vue';
import PageWrapper from "@/components/PageWrapper.vue";
import {DeleteOutlined, DownloadOutlined, ExclamationCircleOutlined, SyncOutlined} from "@ant-design/icons-vue";
import {createVNode, h} from "vue";
import {downloadTheFile} from "@/views/osManager/taskManageComponent/components";

const MAX_UPLOAD_SIZE = 200 * 1024 * 1024;

export default {
  name: 'packageManage',
  data() {
    return {
      uploadLoading: false,
      loading: false,
      fileList: [],
      packageList: [],
      currentPage: 1,
      pageSize: 10,
      selectedRowKeys: [],
      modelList: {
        HEALTH_CHECK: this.$t('packageManage.inspect'),
        DATA_COLLECT: this.$t('packageManage.collect'),
        SECURITY_MANAGE: this.$t('packageManage.security'),
      },
      packageColumns: [
        {
          dataIndex: 'label',
          title: this.$t('packageManage.inspectPackage'),
          sortable: true,
        },
        {
          dataIndex: 'model',
          title: this.$t('packageManage.includeModule'),
          sortable: true,
        },
        {
          dataIndex: 'updateTime',
          title: this.$t('packageManage.uploadTime'),
          sortable: true,
        },
        {
          dataIndex: 'version',
          title: this.$t('packageManage.version'),
        },
        {
          key: 'operation',
          title: this.$t('common.operation'),
          dataIndex: 'operation',
          align: 'center',
        },
      ],
      pagination: {
        sort: null,
        total: 0,
        current: 1,
        pageSize: 10,
        showTotal: total => `${this.$t('common.total', { count: total })}`,
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '30', '40'],
      }
    };
  },
  components: {
    DeleteOutlined,
    DownloadOutlined,
    PageWrapper,
  },
  mounted() {
    this.initPage();
  },
  methods: {
    SyncOutlined,
    h,
    async initPage() {
      this.loading = true;
      const  [_, res] = await api.fnGetInspectionAsset();
      this.packageList = res.asset_infos
        .map(item => {
          item.label = this.$i18n.locale === 'zh' ? item.asset_name.zh : item.asset_name.en;
          item.updateTime = new Date(item.update_time).toLocaleString();
          const modelType = item.support_type.split('|');
          item.model = modelType.map(type => this.modelList[type]).join(' | ');
          return item;
        })
        .reverse();
      this.loading = false;
    },
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    async onPackageUploadSuccess(file) {
      if (file.size >= MAX_UPLOAD_SIZE) {
        message.error(this.$t('packageManage.packageLimitExceeded'));
        this.fileList = [];
        return false;
      }
      Modal.confirm({
        title: () => this.$t('packageManage.warn'),
        icon: () => createVNode(ExclamationCircleOutlined),
        content: () => this.$t('packageManage.packageTip'),
        onOk: async () => {
          this.uploadLoading = true;
          const formData = new FormData();
          formData.append('file', file)
          const [_] = await api.fnUpload(formData);
          if (!_)
            message.success(this.$t('common.uploadSuccess'))
          this.uploadLoading = false;
          this.fileList = [];
          await this.initPage();
        },
      })
      return false
    },
    fnConfirm(message, callback) {
      Modal.confirm({
        title: this.$t('osManager.note'),
        icon: h(ExclamationCircleOutlined),
        content: message,
        okType: 'danger',
        okText: this.$t('osManager.ok'),
        onOk: async () => {
          try {
            callback()
          } catch (error) {
            message.error(error)
          }
        },
      })
    },
    fnBatchDelete() {
      const selectList = this.selectedRowKeys;
      if (!selectList.length) {
        this.fnConfirm(this.$t('packageManage.selectPackageTip'), () => {}, false);
        return;
      }
      const self = this;
      this.fnConfirm(this.$t('packageManage.batchDeletePackageTip'), async function () {
        const [_] = await api.fnDeleteAsset(selectList);
        if (!_)
          message.success(self.$t('common.deleteSuccess'))
        await self.initPage();
      });
    },
    async fnDeletePackage(row) {
      const self = this;
      this.fnConfirm(this.$t('packageManage.deletePackageTip'), async function () {
        const [_] = await api.fnDeleteAsset([row.asset_id]);
        if (!_)
          message.success(self.$t('common.deleteSuccess'))
        await self.initPage();
      });
    },
    async fnDownloadReport(row) {
      const [_, res] = await api.fnDownLoadAsset({ asset_id: row.asset_id });
      if (_.type === 'application/json') {
        await self.initPage();
        return;
      }
      const header = _.headers['content-disposition'].split('=')[1];
      downloadTheFile(res, header);
    },
  },
};
</script>

<style scoped></style>
